import React, { Component } from "react";
import login from "../hooks/loginInfo";
import PageHeader from "../components/PageHeader";
import "../assets/css/Collection.css";
import Bg from "../components/Bg";
import CommodityCard from "../components/CommodityCard";
import Loading from "../components/Loading";

class Collection extends Component {
  constructor(props) {
    super(props);

    this.state = {
      token: null,
      collections: null,
    };
    this.delCollection = this.delCollection.bind(this)
  }

  delCollection(item,e) {
    e.stopPropagation();
    this.$axios.post("/notlike", {
      pid: item.pid,
      tokenString: this.state.token,
    });
    var result = this.state.collections.filter(i=>{
      return i.id !== item.id
    })
    this.setState({
      collections:result
    })
  }

  componentWillMount() {
    var loginInfo = login();
    if (loginInfo.isLogin) {
      this.setState({
        token: loginInfo.token,
      });
      this.$axios
        .get("/findAllLike", {
          params: {
            tokenString: loginInfo.token,
          },
        })
        .then((res) => {
          this.setState({
            collections: res.data.result,
          });
        });
    }
  }

  render() {
    return (
      <div className="Collection">
        <PageHeader>
          <span slot="title">我的收藏</span>
        </PageHeader>
        {this.state.collections ? 
        <React.Fragment>
        {this.state.collections.length <= 0 ? (
          <div className="cart_none">
            <div className="cart_none_empty">
              <img src={require("../assets/images/empty.png").default} alt="" />
              <span>收藏列表空空如也，去逛一逛！</span>
            </div>
            <button
              className="cart_none_btn"
              onClick={() => this.props.history.push("/")}
            >
              去逛一逛
            </button>
          </div>
        ) : (
          <Bg>
            {this.state.collections.map((item) => {
              return (
                <CommodityCard
                  delCollection={(e)=>this.delCollection(item,e)}
                  del={true}
                  item={item}
                  key={item.id}
                ></CommodityCard>
              );
            })}
          </Bg>
        )}
        </React.Fragment> : <Loading></Loading>}
      </div>
    );
  }
}

export default Collection;
